package org.client.iot.ui.device.fragment;

import android.annotation.SuppressLint;
import android.view.View;

import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;

import org.client.iot.databinding.FragmentDeviceParamBinding;
import org.client.iot.domain.DevConfigureDto;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseDevReq;
import org.client.iot.util.MMKVUtils;
import org.client.iot.util.TimeUtils;
import org.tzw.template.base.BaseFragment;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @Author zl
 * @Date 2025/8/20  14:00
 * @Description 配置参数
 */
public class DeviceParamFragment extends BaseFragment<FragmentDeviceParamBinding> {
    private MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected void initListener() {
        mRoot.btnUpdate.setOnClickListener(v -> {
            showToastLong("请修改对应配置参数");
            mRoot.tvDevId.setEnabled(true);
            mRoot.tvDevCycle.setEnabled(true);
            mRoot.tvDevTime.setEnabled(true);
            mRoot.tvDevBasePoint.setEnabled(true);
            mRoot.tvDevMeasureDepth.setEnabled(true);
            mRoot.tvDevZeroPoint.setEnabled(true);
            mRoot.rbDevDirectionUp.setEnabled(true);
            mRoot.rbDevDirectionDown.setEnabled(true);
            mRoot.tvDevCloudStatus.setEnabled(true);
            mRoot.tvDevServerIp.setEnabled(true);
            mRoot.tvDevPort.setEnabled(true);
        });
        mRoot.btnGetDevTime.setOnClickListener(v -> {
            showLoading("获取设备时间中...");
            getDevSetting();
        });
        //加载配置
        mRoot.btnLoading.setOnClickListener(v -> {
            showLoading("加载设备配置中...");
            settingLoad(getDevConfigureDto());
        });
        //上传配置
        mRoot.btnUpload.setOnClickListener(v -> {
            showLoading("上传设备配置中...");
            settingUpload(getDevConfigureDto());
        });
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void initData(View view) {

    }

    private DevConfigureDto getDevConfigureDto() {
        DevConfigureDto devConfigureDto = new DevConfigureDto();
        devConfigureDto.setDeviceModel(Objects.requireNonNull(mRoot.tvDevId.getText()).toString());
        devConfigureDto.setMeasurementCycle(Integer.parseInt(Objects.requireNonNull(mRoot.tvDevCycle.getText()).toString()));
        devConfigureDto.setCalibrateDeviceTime(Objects.requireNonNull(mRoot.tvDevTime.getText()).toString());
        devConfigureDto.setReferencePointPosition(Double.parseDouble(Objects.requireNonNull(mRoot.tvDevBasePoint.getText()).toString()));
        devConfigureDto.setMeasurementDepth(Double.parseDouble(Objects.requireNonNull(mRoot.tvDevMeasureDepth.getText()).toString()));
        devConfigureDto.setSensorZeroPosition(Double.parseDouble(Objects.requireNonNull(mRoot.tvDevZeroPoint.getText()).toString()));
        devConfigureDto.setMeasurementDirection(mRoot.rbDevDirectionUp.isChecked() ? "正向测量" : "反向测量");
        devConfigureDto.setServerIP(Objects.requireNonNull(mRoot.tvDevServerIp.getText()).toString());
        devConfigureDto.setServerPort(Objects.requireNonNull(mRoot.tvDevPort.getText()).toString());
        devConfigureDto.setNetworkAccess(Objects.requireNonNull(mRoot.tvDevCloudStatus.getText()).toString());
        return devConfigureDto;
    }

    // 获取设备配置
    private void getDevSetting() {
        Observable<BaseDevReq<DevConfigureDto>> compose = NetworkApi.createService(ApiService.class, "dev").getDevSetting().compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<DevConfigureDto>>() {
            @SuppressLint({"CheckResult", "SetTextI18n"})
            @Override
            public void onSuccess(BaseDevReq<DevConfigureDto> req) {
                if (req == null) {
                    return;
                }
                requireActivity().runOnUiThread(() -> {
                    disLoading();
                    LogUtils.i("获取设备配置req==", req.toString());
                    if (req.getData() != null) {
                        mRoot.tvDevId.setText(req.getData().getDeviceModel());
                        mRoot.tvDevCycle.setText(req.getData().getMeasurementCycle() + "");
                        mRoot.tvDevTime.setText(TimeUtils.formatDateTime(req.getData().getCalibrateDeviceTime()));
                        mRoot.tvDevBasePoint.setText(req.getData().getReferencePointPosition() + "");
                        mRoot.tvDevMeasureDepth.setText(req.getData().getMeasurementDepth() + "");
                        mRoot.tvDevZeroPoint.setText(req.getData().getSensorZeroPosition() + "");
                        String direction = req.getData().getMeasurementDirection();
                        if (!direction.isEmpty()) {
                            if ("正向测量".equals(direction)) {
                                mRoot.rbDevDirectionUp.setChecked(true);
                            } else if ("反向测量".equals(direction)) {
                                mRoot.rbDevDirectionDown.setChecked(true);
                            }
                        }
                        mRoot.tvDevServerIp.setText(req.getData().getServerIP());
                        mRoot.tvDevPort.setText(req.getData().getServerPort());
                        mRoot.tvDevCloudStatus.setText(req.getData().getNetworkAccess());
                        MMKVUtils.getInstance().put("DevServerIP", req.getData().getServerIP());
                        MMKVUtils.getInstance().put("DevServerPort", req.getData().getServerPort());
                    }
                });
            }

            @SuppressLint("CheckResult")
            @Override
            public void onFailure(Throwable e) {
                requireActivity().runOnUiThread(() -> {
                    disLoading();
                    showToastLong(e.getMessage());
                });
            }

        }));
    }

    // 加载设备配置
    private void settingLoad(DevConfigureDto devConfigureDto) {
        String params = FastjsonUtils.toJsonString(settingLoadParams(devConfigureDto));
        Observable<BaseDevReq<Object>> compose = NetworkApi.createService(ApiService.class, "dev")
                .settingLoad(RequestBody.create(MediaType.parse("application/json"), params))
                .compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
                    @SuppressLint({"CheckResult", "SetTextI18n"})
                    @Override
                    public void onSuccess(BaseDevReq<Object> req) {
                        if (req == null) {
                            return;
                        }
                        requireActivity().runOnUiThread(() -> {
                            disLoading();
                            LogUtils.i("加载设备配置req==", req.toString());
                            showToastLong(req.getMessage());
                        });
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        requireActivity().runOnUiThread(() -> {
                            disLoading();
                            showToastLong(e.getMessage());
                        });
                    }

                }));
    }

    // 上传设备配置接口
    private void settingUpload(DevConfigureDto devConfigureDto) {
        String params = FastjsonUtils.toJsonString(settingLoadParams(devConfigureDto));
        Observable<BaseDevReq<Object>> compose = NetworkApi.createService(ApiService.class, "dev")
                .settingUpload(RequestBody.create(MediaType.parse("application/json"), params))
                .compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
                    @SuppressLint({"CheckResult", "SetTextI18n"})
                    @Override
                    public void onSuccess(BaseDevReq<Object> req) {
                        if (req == null) {
                            return;
                        }
                        requireActivity().runOnUiThread(() -> {
                            disLoading();
                            LogUtils.i("上传设备配置req==", req.toString());
                            showToastLong(req.getMessage());
                        });
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        requireActivity().runOnUiThread(() -> {
                            disLoading();
                            showToastLong(e.getMessage());
                        });
                    }

                }));
    }

    private Map<String, Object> settingLoadParams(DevConfigureDto devConfigureDto) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("deviceModel", devConfigureDto.getDeviceModel());
        params.put("measurementCycle", devConfigureDto.getMeasurementCycle());
        params.put("calibrateDeviceTime", devConfigureDto.getCalibrateDeviceTime());
        params.put("referencePointPosition", devConfigureDto.getReferencePointPosition());
        params.put("measurementDepth", devConfigureDto.getMeasurementDepth());
        params.put("sensorZeroPosition", devConfigureDto.getSensorZeroPosition());
        params.put("measurementDirection", devConfigureDto.getMeasurementDirection());
        params.put("serverIP", devConfigureDto.getServerIP());
        params.put("serverPort", devConfigureDto.getServerPort());
        params.put("networkAccess", devConfigureDto.getNetworkAccess());
        return params;
    }

    private void showLoading(String msg) {
        requireActivity().runOnUiThread(() -> {
            mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(requireActivity(), msg);
            mMiniLoadingDialog.show();
        });
    }

    private void disLoading() {
        requireActivity().runOnUiThread(() -> {
            if (mMiniLoadingDialog != null) {
                mMiniLoadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        showLoading("获取设备配置中...");
        getDevSetting();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disLoading();
    }
}